#Encoding: UTF-8
class FriendshipController < ApplicationController

  include ProfileHelper
  before_filter :protect, :setup_friends
  # Send a friend request.
  # We'd rather call this "request", but that's not allowed by Rails.
  def create
    Friendship.request(@user, @friend)
    UserMailer.deliver_friend_request(
    :user => @user,
    :friend => @friend,
    :user_url => profile_for(@user),
    :accept_url => url_for(:action => "accept", :id => @user.screen_name),
    :decline_url => url_for(:action => "decline", :id => @user.screen_name)
    ).deliver
    flash[:notice] = "Solicitud de amistad enviada."
    redirect_to profile_for(@friend)
  end

  def accept
    if @user.requested_friends.include?(@friend)
      Friendship.accept(@user, @friend)
      flash[:notice] = "Amistad con #{@friend.screen_name} aceptada!"
    else
      flash[:notice] = "No existe solicitud de amistad de #{@friend.screen_name}."
    end
    redirect_to hub_url
  end

  def decline
    if @user.requested_friends.include?(@friend)
      Friendship.breakup(@user, @friend)
      flash[:notice] = "Amistad con #{@friend.screen_name} declinada"
    else
      flash[:notice] = "No existe solicitud de amistad de #{@friend.screen_name}."
    end
    redirect_to hub_url
  end

  def cancel
    if @user.pending_friends.include?(@friend)
      Friendship.breakup(@user, @friend)
      flash[:notice] = "Solicitud de amistad cancelada."
    else
      flash[:notice] = "No existe solicitud de amistad de #{@friend.screen_name}"
    end
    redirect_to hub_url
  end

  def delete
    if @user.friends.include?(@friend)
      Friendship.breakup(@user, @friend)
      flash[:notice] = "Amistad con #{@friend.screen_name} eliminada!"
    else
      flash[:notice] = "Tu no eres amigo de #{@friend.screen_name}"
    end
    redirect_to hub_url
  end

  private

  def setup_friends
    @user = User.find(session[:user_id])
    @friend = User.find_by_screen_name(params[:id])
  end
end

